<template>
    <div class="common-layout">
    <el-container>
      <el-header>
        <!--条件查询-->
        <el-form :inline="true" :model="chaForm" class="demo-form-inline">
            <el-form-item label="建档日期">
                <el-date-picker
                    v-model="chaForm.CreateStartTime"
                    type="date"
                    placeholder="Pick a day"
                    :size="size"
                />  ~  
                <el-date-picker
                    v-model="chaForm.CreateEndTime"
                    type="date"
                    placeholder="Pick a day"
                    :size="size"
                />
            </el-form-item>&nbsp;&nbsp;
            <el-form-item label="姓名">
                <el-input v-model="chaForm.ResidentFiles_Name" placeholder="请输入居民名称" clearable />
            </el-form-item>

            <el-form-item>
                <el-button type="primary" @click="getResidentFileList()">查询</el-button>
            </el-form-item>

          </el-form>
      </el-header>
      <el-main>
<el-button style="background-color: yellowgreen;" plain @click="dialogFormVisible = true">+ 建档</el-button>&nbsp;
<el-button type="info" @click="importResidentFile()">导入</el-button>&nbsp;
<el-button type="primary" @click="exportData">导出</el-button>
<!--居民档案列表-->
        <el-table :data="tableData" style="width: 100%">
    <el-table-column type="selection" width="55" />
    <el-table-column property="residentFiles_Id" label="编号" width="120" />
    <el-table-column property="residentFiles_Name" label="姓名" width="180"/>
    <el-table-column property="age" label="年龄" width="120"/>
    <el-table-column property="idCard" label="身份证号" width="120"/>
    <el-table-column property="phone" label="联系电话" width="120"/>
    <el-table-column property="address" label="家庭地址" width="120"/>
    <el-table-column property="teamName" label="签约团队" width="120"/>
    <el-table-column property="createTime" label="建档日期" width="120"/>
    <el-table-column property="sign_Status" label="状态" width="120">
        <template v-slot="scoped">
        <el-tag  effect="dark" round>
      {{ scoped.row.sign_Status == 0? "未签约" : scoped.row.sign_Status == null? "未签约" : "已签约" }}
       </el-tag>        
      </template>
    </el-table-column>
    <el-table-column fixed="right" label="操作" min-width="120">
    <template v-slot="scope">
      <el-button style="background-color:green;color:red;"  plain @click="goResidentFileDetail(scope.row.residentFiles_Id)">详情</el-button>    
    </template>
  </el-table-column>
  </el-table>
    <!--分页-->
    <table style="margin: 15px auto;">
    <tbody>
        <tr>
            <!--总页数-->
            <td>
                <el-pagination
      v-model:current-page="page.pageIndex"
      v-model:page-size="page.pageSize"
      :page-sizes="[2, 4, 6, 8]"
      :background="true"
      layout=" total,slot,sizes"    
      :total="page.totalCount" prev-text="上一页" next-text="下一页"
    >
<span>每页{{ page.pageSize }}条,共{{ page.pageIndex }}/{{ page.totalPage }}行</span>
                </el-pagination>
            </td>
            <!--首页-->
            <td>
                <el-pagination
      v-model:current-page="page.pageIndex"
      v-model:page-size="page.pageSize"
      :page-sizes="[2, 4, 6, 8]"
      :background="true"
      layout=" solt,prev,pager,next"    
      :total="page.totalCount" prev-text="上一页" next-text="下一页">
      <button class="btn-prev" :disabled="page.pageIndex==1" @click="page.pageIndex=1">首页</button>
            </el-pagination>
            </td>
            <!--尾页-->
            <td>
                <el-pagination
      v-model:current-page="page.pageIndex"
      v-model:page-size="page.pageSize"
      :page-sizes="[2, 4, 6, 8]"
      :background="true"
      layout=" solt,jumper"    
      :total="page.totalCount" prev-text="上一页" next-text="下一页">
      <button class="btn-next" :disabled="page.pageIndex==page.totalPage" @click="page.pageIndex=page.totalPage">尾页</button>
            </el-pagination>
            </td>
        </tr>
    </tbody>
  </table>
      </el-main>
    </el-container>
  </div>
  <!-- 弹出框添加 -->
  <!-- 添加居民档案弹窗 -->
        <el-dialog v-model="dialogFormVisible" title="居民建档" width="40%">
          <el-tabs v-model="activeName" class="demo-tabs" @tab-click="handleClick">
            <el-tab-pane label="基础档案" name="first">
              <!-- 基础档案信息表单内容 -->
              <el-form :model="residentForm" >
                <el-row :gutter="50">
                  <el-col :span="12">
                    <el-form-item label="姓名">
                      <el-input v-model="residentForm.residentFiles_Name" style="width: 13vw;
    height: 3vh;" />
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="性别">
                      <el-radio-group v-model="residentForm.sex">
                        <el-radio :label="true">男</el-radio>
                        <el-radio :label="false">女</el-radio>
                      </el-radio-group>
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row :gutter="20">
                  <el-col :span="12">
                    <el-form-item label="年龄">
                      <el-input v-model="residentForm.age" type="number" style="width: 13vw;
    height: 3vh;"/>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="身份证号">
                      <el-input v-model="residentForm.idCard" style="width: 13vw;
    height: 3vh;"/>
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row :gutter="20">
                  <el-col :span="12">
                    <el-form-item label="联系电话">
                      <el-input v-model="residentForm.phone" style="width: 13vw;
    height: 3vh;"/>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="出生日期">
                      <el-date-picker v-model="residentForm.birthday" type="date" placeholder="选择日期" style="width: 13vw;
    height: 3vh;"/>
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-form-item label="家庭地址">
                  <el-input v-model="residentForm.address" style="width: 13vw;
    height: 3vh;"/>
                </el-form-item>
                <el-row :gutter="20">
                  <el-col :span="12">
                    <el-form-item label="婚姻状况">
                      <el-input v-model="residentForm.marriage" style="width: 13vw;
    height: 3vh;"/>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="血型">
                      <el-input v-model="residentForm.bloodType" style="width: 13vw;
    height: 3vh;"/>
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row :gutter="20">
                  <el-col :span="12">
                    <el-form-item label="参保情况">
                      <el-input v-model="residentForm.insuredSituation" style="width: 13vw;
    height: 3vh;"/>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="职业">
                      <el-input v-model="residentForm.job" style="width: 13vw;
    height: 3vh;" />
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-form-item label="文化程度">
                  <el-input v-model="residentForm.education" style="width: 13vw;
    height: 3vh;"/>
                </el-form-item>
              </el-form>
            </el-tab-pane>
            <el-tab-pane label="行为信息" name="second">
              <!-- 行为信息表单内容 -->
                <el-form :model="residentForm" style="display:flex;align-items:center;flex-direction:column;">
                <el-form-item label="是否吸烟">
                  <el-select v-model="residentForm.ifSmoke" placeholder="请选择" style="width: 15vw;
    height: 3vh;">
                    <el-option label="是" :value=true></el-option>
                    <el-option label="否" :value=false></el-option>
                  </el-select>
                </el-form-item>
                <el-form-item label="是否戒烟者">
                  <el-select v-model="residentForm.ifQuitSmoke" placeholder="请选择" style="width: 15vw;
    height: 3vh;">
                    <el-option label="是" :value=true></el-option>
                    <el-option label="否" :value=false></el-option>
                  </el-select>
                </el-form-item>
                <el-form-item label="是否被动吸烟者">
                  <el-select v-model="residentForm.ifPassiveSmoke" placeholder="请选择" style="width: 15vw;
    height: 3vh;">
                    <el-option label="是" :value=true></el-option>
                    <el-option label="否" :value=false></el-option>
                  </el-select>
                </el-form-item>
                <el-form-item label="是否饮酒">
                  <el-select v-model="residentForm.ifDrinkWine" placeholder="请选择" style="width: 15vw;
    height: 3vh;">
                    <el-option label="是" :value=true></el-option>
                    <el-option label="否" :value=false></el-option>
                  </el-select>
                </el-form-item>
                <el-form-item label="是否运动">
                  <el-select v-model="residentForm.ifSport" placeholder="请选择" style="width: 15vw;
    height: 3vh;">
                    <el-option label="充分" value="0"></el-option>
                    <el-option label="中等" value="1"></el-option>
                    <el-option label="不足" value="2"></el-option>
                  </el-select>
                </el-form-item>
                <el-form-item label="高血压知晓情况">
                  <el-select v-model="residentForm.hypertension" placeholder="请选择" style="width: 15vw;
    height: 3vh;">
                    <el-option label="患有高血压" value="0"></el-option>
                    <el-option label="血压正常" value="1"></el-option>
                    <el-option label="从未测量" value="2"></el-option>
                  </el-select>
                </el-form-item>
                <el-form-item label="糖尿病知晓情况">
                  <el-select v-model="residentForm.diabetes" placeholder="请选择" style="width: 15vw;
    height: 3vh;">
                    <el-option label="患有糖尿病" value="0"></el-option>
                    <el-option label="血糖正常" value="1"></el-option>
                  </el-select>
                </el-form-item>
              </el-form>
            </el-tab-pane>
            <el-tab-pane label="体格信息" name="third">
              <!-- 体格信息表单内容 -->
                  <el-form :model="residentForm" style="display:flex;align-items:center;flex-direction:column;">
                <el-form-item label="身高">
                  <el-input v-model.number="residentForm.height" placeholder="请输入身高（cm）" style="width: 15vw;
    height: 3vh;"></el-input>
                </el-form-item>
                <el-form-item label="体重">
                  <el-input v-model.number="residentForm.weight" placeholder="请输入体重（kg）" style="width: 15vw;
    height: 3vh;"></el-input>
                </el-form-item>
                <el-form-item label="BMI">
                  <el-input v-model.number="residentForm.bmi" placeholder="请输入BMI值" disabled style="width: 15vw;
    height: 3vh;"></el-input>
                </el-form-item>
                <el-form-item label="腰围">
                  <el-input v-model.number="residentForm.waistline" placeholder="请输入腰围（cm）" style="width: 15vw;
    height: 3vh;"></el-input>
                </el-form-item>
                <el-form-item label="收缩压">
                  <el-input v-model.number="residentForm.systolicPressure" placeholder="请输入收缩压（mmHg）" style="width: 15vw;
    height: 3vh;"></el-input>
                </el-form-item>
                <el-form-item label="舒张压">
                  <el-input v-model.number="residentForm.siastolicPressure" placeholder="请输入舒张压（mmHg）" style="width: 15vw;
    height: 3vh;"></el-input>
                </el-form-item>
                <el-form-item label="空腹血糖">
                  <el-input v-model.number="residentForm.fastingBloodGlucose" placeholder="请输入空腹血糖（mmol/L）" style="width: 15vw;
    height: 3vh;"></el-input>
                </el-form-item>
              </el-form>
            </el-tab-pane>
          </el-tabs>

          <template #footer>
            <span class="dialog-footer">
              <el-button @click="dialogFormVisible = false">取消</el-button>
              <el-button type="primary" @click="addResidentFile">保存</el-button>
            </span>
          </template>
        </el-dialog>
</template>

<script setup lang="ts">
import axios from 'axios';
import { ElMessage, ElMessageBox ,ElLoading} from 'element-plus'; // 引入 ElMessage 和 ElMessageBox
import moment from 'moment';
import { onMounted, reactive, ref,watch } from 'vue'
import { useRouter, useRoute } from 'vue-router';
import { regionData } from "element-china-area-data";//引入
import { useCounterStore } from '@/stores/counter';
import type { TreeInstance } from 'element-plus'
import type { TabsPaneContext } from 'element-plus'
const apiUrl = import.meta.env.VITE_APP_API_URL;
// console.log(regionData)
//pini保存
const store = useCounterStore();
//跳转

const router = useRouter();
const formLabelWidth = '140px'
const activeName = ref('first')
const handleClick = (tab: TabsPaneContext, event: Event) => {
  console.log(tab, event)
}
//查询参数
const chaForm = reactive({
    CreateStartTime:"",
    CreateEndTime:"",
    ResidentFiles_Name:"",
    PageIndex:1,
    PageSize:15
})
//分页的参数
const page = reactive({
    pageIndex:1,
    pageSize:15,
    totalCount:0,
    totalPage:0
})

//分页数据
const tableData =ref([])
//居民档案查询方法
const getResidentFileList=()=>{
    axios.get(apiUrl+"/T7/ResidentFiles/GetResidentFilesList",{
      params:{
          PageIndex:page.pageIndex,
          PageSize:page.pageSize,
          CreateStartTime:chaForm.CreateStartTime,
          CreateEndTime:chaForm.CreateEndTime,
          ResidentFiles_Name:chaForm.ResidentFiles_Name
      }
  }).then(res=>{
    console.log("查看居民档案列表数据",res.data);
      tableData.value = res.data.list;
      page.totalCount = res.data.totalCount;
      page.totalPage = res.data.totalPage;
  })
}
//居民档案详情跳转页面
const goResidentFileDetail=(id:any)=>{
    router.push({
        path:"/ResidentFileDetail",
        query:{
            id:id
        }
    })
}
// 弹窗显示状态
const dialogFormVisible = ref(false);

// 表单数据
const residentForm = reactive({
  residentFiles_Id: 0,
  residentFiles_Name: "",
  sex: true,
  age: null,
  idCard: "",
  phone: "",
  birthday: "",
  address: "",
  marriage: "",
  bloodType: "",
  insuredSituation: "",
  job: "",
  education: "",
  ifSmoke: null,
  ifQuitSmoke: null,
  ifPassiveSmoke: null,
  ifDrinkWine: null,
  ifSport: null,
  hypertension: null,
  diabetes: null,
  height: null,
  weight: null,
  bmi: null,
  waistline: null,
  systolicPressure: null,
  siastolicPressure: null,
  fastingBloodGlucose: null,
  createUser: "",
  createTime: "",
  updateUser: "",
  updateTime: ""
});

// 添加居民档案方法
const addResidentFile = () => {
  // 格式化日期
  residentForm.birthday = moment(residentForm.birthday).format('YYYY-MM-DD');
  residentForm.createTime = new Date().toISOString(); // 设置当前时间
  residentForm.updateTime = new Date().toISOString(); // 设置当前时间
  residentForm.createUser = store.ccstore.userName;
  residentForm.updateUser = store.ccstore.userName;
  axios.post(apiUrl+"/T8/ResidentFile/AddResidentFiles", residentForm)
    .then(res => {
      if (res.data.code == 212) {
        ElMessage.success(res.data.msg);
        dialogFormVisible.value = false;
        getResidentFileList(); // 刷新列表
      } else {
        ElMessage.error(res.data.msg);
      }
    })
    .catch(err => {
      ElMessage.error('请求失败');
      console.error(err);
    });
};

//导出居民档案数据
const exportData = () => {
    axios.get(apiUrl+"/T8/ResidentFile/Export", {
        responseType: 'blob' // 指定响应类型为 blob，以处理文件下载
    }).then(response => {
        // 创建一个临时链接来下载文件
        const url = window.URL.createObjectURL(new Blob([response.data]));
        const link = document.createElement('a');
        link.href = url;
        link.setAttribute('download', '居民档案信息.xlsx'); // 设置下载文件的名称
        document.body.appendChild(link);
        link.click();
        link.remove();
        window.URL.revokeObjectURL(url);
    }).catch(error => {
        ElMessage.error('导出失败: ' + error.message);
    });
};
// 导入居民档案信息
const importResidentFile = () => {
  ElMessageBox.confirm('您确定要导入居民档案吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    // 创建文件输入元素
    const input = document.createElement('input')
    input.type = 'file'
    input.accept = '.xlsx,.xls,.csv' // 限制文件类型
      
    input.click() // 触发文件选择

    input.onchange = async (e) => {
       const fileInput = e.target as HTMLInputElement;
    const file = fileInput.files?.[0];
      if (!file) return
      
      // 验证文件类型
      const validTypes = ['application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', 
                         'application/vnd.ms-excel',
                         'text/csv']
      if (!validTypes.includes(file.type)) {
        ElMessage.error('请上传Excel或CSV文件')
        return
      }
      
      // 创建FormData
      const formData = new FormData()
      formData.append('file', file)
      
      try {
        // 显示加载中
        const loading = ElLoading.service({
          lock: true,
          text: '文件上传中...',
          background: 'rgba(0, 0, 0, 0.7)'
        })
        
        // 使用axios上传
        const response = await axios.post(apiUrl+'/T8/ResidentFile/ImportResidentFiles', formData,  
          {
            headers: {
              'Content-Type': 'multipart/form-data'
            }
          }
        )
        
        loading.close()
        
        if (response.data.code === 200) {
          ElMessage.success('导入成功')
          getResidentFileList() // 刷新列表
        } else {
          ElMessage.error(response.data.msg || '导入失败')
        }
      } catch (error) {
        ElMessage.error(`导入失败: ${error.message}`)
        console.error('导入错误:', error)
      }
    }
  
  }).catch(() => {
    ElMessage.info('已取消导入')
  })
}
//分页监听器
watch(page,()=>{
    getResidentFileList();
})
watch([() => residentForm.height, () => residentForm.weight], ([newHeight, newWeight]) => {
  if (newHeight > 0 && newWeight >= 0) {
    residentForm.bmi = parseFloat((newWeight / Math.pow(newHeight / 100, 2)).toFixed(2));
  } else {
    residentForm.bmi = 0; // 或者其他默认值
  }
}, { immediate: true }); // immediate: true 表示初始化时也执行一次


//构造函数
onMounted(()=>{
    getResidentFileList();//居民档案列表
})


</script>

<style scoped>
/* 全局样式规范 */
:root {
  /* 企业主色（建议使用品牌色） */
  --primary-color: #409eff;
  /* 辅助色 */
  --success-color: #67c23a;
  --warning-color: #f90;
  --danger-color: #f56c6c;
  --info-color: #909399;
  
  /* 字体规范 */
  --font-primary: "PingFang SC", "Helvetica Neue", Helvetica, Arial, sans-serif;
  --font-size-base: 14px;
  --font-size-lg: 16px;
  --font-weight-medium: 500;
  
  /* 间距规范 */
  --padding-base: 16px;
  --margin-base: 12px;
  --line-height-base: 1.5;
  
  /* 表格样式 */
  --table-row-height: 44px;
}

/* 全局基础样式 */
.common-layout {
  font-family: var(--font-primary);
  font-size: var(--font-size-base);
  line-height: var(--line-height-base);
  color: #303133;
}

.el-container {
  min-height: 100vh;
}

.el-header {
  padding: var(--padding-base);
  background-color: #f5f7fa;
  border-bottom: 1px solid #ebedf0;
}

.el-main {
  padding: var(--padding-base 24px);
  background-color: #fff;
}

/* 表单样式优化 */
.demo-form-inline {
  display: flex;
  align-items: center;
  gap: var(--margin-base);
}

.el-form-item {
  margin-bottom: 0;
}

.el-input,
.el-select {
  height: 40px;
  border-radius: 4px;
}

/* 按钮样式规范（统一使用组件内置类型，避免内联样式） */
.el-button {
  font-size: var(--font-size-base);
  border-radius: 4px;
  padding: 0 16px;
}

.el-button.primary {
  background-color: var(--primary-color);
  border-color: var(--primary-color);
}

.el-button.success {
  background-color: var(--success-color);
  border-color: var(--success-color);
}

.el-button.warning {
  background-color: var(--warning-color);
  border-color: var(--warning-color);
}

.el-button.danger {
  background-color: var(--danger-color);
  border-color: var(--danger-color);
}

/* 表格样式优化 */
.el-table {
  margin-top: var(--margin-base);
  border-radius: 8px;
  overflow: hidden;
}

.el-table__header-wrapper {
  background-color: #f5f7fa;
}

.el-table__row {
  height: var(--table-row-height);
}

.el-table__cell {
  padding: 0 16px;
  border-bottom: 1px solid #ebedf0;
  font-size: var(--font-size-base);
}

.el-table--striped .el-table__body tr.el-table__row--striped {
  background-color: #f9fafc;
}

/* 状态标签样式 */
.el-tag {
  font-size: var(--font-size-base);
  padding: 4px 12px;
}

/* 弹窗样式优化 */
.el-dialog {
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
}

.el-dialog__header {
  padding: var(--padding-base);
  background-color: #f5f7fa;
  border-bottom: 1px solid #ebedf0;
}

.el-dialog__title {
  font-size: var(--font-size-lg);
  font-weight: var(--font-weight-medium);
}

.el-dialog__body {
  padding: var(--padding-base 24px);
}

.el-form-item {
  margin-bottom: 20px;
}

/* 分页样式优化 */
.el-pagination {
  display: flex;
  align-items: center;
  gap: 8px;
  justify-content: flex-end; /* 建议右对齐，符合企业规范 */
}

.el-pagination__sizes {
  margin-right: var(--margin-base);
}

.el-pagination__editor {
  width: 60px;
  margin: 0 8px;
}

/* 操作按钮组样式 */
.el-table__fixed-right {
  padding-right: 16px; /* 固定列右侧间距 */
}

.table-operation {
  display: flex;
  gap: 8px;
}

/* 禁用状态样式 */
[disabled],
.disabled {
  opacity: 0.6;
  cursor: not-allowed;
}
.demo-date-picker {
  display: flex;
  width: 100%;
  padding: 0;
  flex-wrap: wrap;
}

.demo-date-picker .block {
  padding: 30px 0;
  text-align: center;
  border-right: solid 1px var(--el-border-color);
  flex: 1;
}

.demo-date-picker .block:last-child {
  border-right: none;
}

.demo-date-picker .demonstration {
  display: block;
  color: var(--el-text-color-secondary);
  font-size: 14px;
  margin-bottom: 20px;
}

.demo-tabs > .el-tabs__content {
  padding: 32px;
  color: #6b778c;
  font-size: 32px;
  font-weight: 600;
}
/* 响应式优化 */
@media (max-width: 768px) {
  .el-main {
    padding: var(--padding-base);
  }
  
  .el-table {
    font-size: 13px;
  }
}
</style>